package cn.flying.cloud.file.core.ocr.service;

import javax.annotation.Resource;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import cn.flying.cloud.base.common.utils.Ft;
import cn.flying.cloud.file.core.ocr.enums.DataTypeEnum;
import cn.flying.cloud.file.core.ocr.enums.OcrTypeEnum;
import cn.flying.cloud.file.core.ocr.wx.WxOcrService;
import cn.flying.cloud.file.core.service.FileService;
import cn.flying.cloud.file.model.FileRequest;

/**
 * OCR服务接口
 *
 * @author: admin
 * @date: 2025年07月25日 15:56
 * @version: 1.0
 */
@Component
public class OCRService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private FileService fileService;
    @Resource
    private WxOcrService wxOcrService;

    /**
     * 上传文件并OCR识别
     *
     * @param file        文件
     * @param bucketName  桶
     * @param ocrType     OCR类别
     * @param serviceCode 服务码
     * @return
     * @throws Exception
     */
    public Map<String, Object> ocrAllInOne(MultipartFile file, String bucketName, Integer ocrType, String serviceCode) throws Exception {
        FileRequest req = new FileRequest();
        req.setRequestNo(UUID.randomUUID().toString().replaceAll("-", ""));
        if (Ft.String.isBlank(serviceCode)) {
            serviceCode = "default";
        }
        req.setTenantId(Ft.Local.TenantId());
        req.setServiceCode(serviceCode);
        req.setBucketName(bucketName);
        req.setFileName(file.getOriginalFilename());
        req.setContent(file.getBytes());

        String path = fileService.uploadFile(req);

        OcrTypeEnum ocrTypeEnum = OcrTypeEnum.valueOfByType(ocrType);
        String encode = Base64.getEncoder().encodeToString(file.getBytes());
        Map<String, String> ocrData = wxOcrService.ocrAllInOne(null, encode, DataTypeEnum.BASE64, ocrTypeEnum);

        Map<String, Object> data = new HashMap<>();
        data.put("filePath", path);
        data.put("ocrInfo", ocrData);

        return data;
    }

    /**
     * OCR识别
     *
     * @param file    文件
     * @param ocrType OCR类别
     * @return
     * @throws Exception
     */
    public Map<String, Object> ocrAllInOne(MultipartFile file, Integer ocrType) throws Exception {
        String encode = Base64.getEncoder().encodeToString(file.getBytes());
        OcrTypeEnum ocrTypeEnum = OcrTypeEnum.valueOfByType(ocrType);
        Map<String, String> ocrData = wxOcrService.ocrAllInOne(null, encode, DataTypeEnum.BASE64, ocrTypeEnum);

        Map<String, Object> data = new HashMap<>();
        data.put("ocrInfo", ocrData);

        return data;
    }
}
